package libra.tracking;

import org.apache.skywalking.apm.toolkit.trace.Tag;
import org.apache.skywalking.apm.toolkit.trace.Tags;
import org.apache.skywalking.apm.toolkit.trace.Trace;
import org.apache.skywalking.apm.toolkit.trace.TraceContext;
import org.springframework.stereotype.Service;

/**
 * 使用apm-toolkit-trace依赖中的支持,采取自定义的链路监控
 * 注解支持：
 * 	@Trace
 * 	@Tags
 * 	@Tag
 * 方法支持：
 * 	TraceContext
 * 		putCorrelation()
 * 		getCorrelation()
 * 		segmentId()
 * 		spanId()
 * 		traceId()
 */
@Service
public class UseService {
	// 通过@Trace标注当前执行方法需要被追踪
	@Trace
	@Tags({
		@Tag(key = "param_1",value = "arg[0]"),
		@Tag(key = "param_2",value = "arg[1]"),
		@Tag(key = "param_3",value = "arg[2]")
	})
	public void doService( int i1, int i2, int i3 ) {
		doCache();
		doDB();
		doMQ();
	}
	
	@Trace
	@Tag(key = "result",value = "returnObj")
	public Object doMQ() {
		try {
			// 通过上下文对象获取当前链路的traceID
			String traceId = TraceContext.traceId();
			System.out.println("通过TraceContext获取当前链路TraceID，from[doMQ()]：" + traceId);
			
			int spanId = TraceContext.spanId();
			System.out.println("通过TraceContext获取当前链路SpanId，from[doMQ()]：" + spanId);
			
			String segmentId = TraceContext.segmentId();
			System.out.println("通过TraceContext获取当前链路segmentId，from[doMQ()]：" + segmentId);

			Thread.sleep(2000);
		} catch (InterruptedException e) {
			e.printStackTrace();
		}
		return null;
	}
	
	@Trace
	public void doDB() {
		try {
			// 通过上下文对象获取当前链路的traceID
			String traceId = TraceContext.traceId();
			System.out.println("通过TraceContext获取当前链路TraceID，from[doDB()]：" + traceId);
			
			int spanId = TraceContext.spanId();
			System.out.println("通过TraceContext获取当前链路SpanId，from[doDB()]：" + spanId);
			
			String segmentId = TraceContext.segmentId();
			System.out.println("通过TraceContext获取当前链路SegmentId，from[doDB()]：" + segmentId);

			Thread.sleep(1000);
		} catch (InterruptedException e) {
			e.printStackTrace();
		}
	}
	
	@Trace(operationName = "do_cache")
	public void doCache() {
		// 通过上下文对象对绑定参数(key/value)通过key进行获取，返回的是个option
		String data = TraceContext.getCorrelation("data").get();
		System.out.println("通过TraceContext获取寄存变量：" + data);
		// 通过上下文对象获取当前链路的traceID
		String traceId = TraceContext.traceId();
		System.out.println("通过TraceContext获取当前链路TraceID，from[doCache()]：" + traceId);
	}
}
